package eval;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class Evaluator {
    HashMap<String, HashMap<String,Integer>> confusionCount;
    HashMap<String, Integer> totalCount;
    ArrayList<String[]> arr;
    public Boolean PRINT_MATRIX;

    public Evaluator(ArrayList<String[]> arr){
	this.arr = arr;
	confusionCount = new HashMap<String, HashMap<String,Integer>>();
	totalCount = new HashMap<String, Integer>();
	PRINT_MATRIX = true;
    }
    public double run(){

	for( String[] str : arr){
	    if(totalCount.containsKey(str[1]))
		totalCount.put(str[1], totalCount.get(str[1])+1); //increment total count
	    else
		totalCount.put(str[1], 1);

		if(confusionCount.containsKey(str[1])){ //word
		    //TODO contains type key
		    int val = 0;

		    if(confusionCount.get(str[1]).containsKey(str[2]))
			val = confusionCount.get(str[1]).get(str[2]);
		    else
			confusionCount.get(str[1]).put(str[2], 1);
		    confusionCount.get(str[1]).put(str[2], ++val);
		}else{
		    final String tmp = str[2];
		    confusionCount.put(str[1], new HashMap<String, Integer>(){{put(tmp ,1);}});
		}
	}
	
	if(PRINT_MATRIX)
	    printConfusionMatrix();
	return findAccuracy();
    }
    public double findAccuracy(){
	double result = 0;
	double i = 0;
	for(String[] str : arr){
	    if(str[1].equals(str[2]))
		result++;
	    i++;
	}
	return result / (double)i;
    }
    public void printConfusionMatrix(){
	//Print Line:A

	String line = "";
	for(Map.Entry<String, Integer> firstrow : totalCount.entrySet()){
	    line += "\t" + firstrow.getKey();
	}
	System.out.println(line);

	for(Map.Entry<String, Integer> pos : totalCount.entrySet()){
	    line = pos.getKey(); 
	    double posCount = pos.getValue();
	    for(Map.Entry<String, Integer> ppos : totalCount.entrySet()){
		line += "\t";
		if(confusionCount.get(pos.getKey()).containsKey(ppos.getKey()))
		    line += String.format("%.2f", (double)(confusionCount.get(pos.getKey()).get(ppos.getKey())/posCount*100)) + "%";
		else
		    line += "x";
	    }
	    System.out.println(line);
	}

    }

}
